package web

import (
	"go-quick/interface/ilogger"
	"go-quick/interface/iweb"
	"go-quick/utils"
	"net"
	"net/http"
	"net/url"
	"strings"
)

type HttpRequest struct {
	RequestQuery
	RequestParam
	request            *http.Request
	query              iweb.IQuery
	param              iweb.IParam
	body               iweb.IBody
	log                ilogger.ILogger
	formCache          url.Values
	paramCache         iweb.IRouterParams
	maxMultipartMemory int64
}

func NewHttpRequest(logger ilogger.ILogger, req *http.Request) *HttpRequest {
	h := &HttpRequest{
		log:     logger,
		request: req,
	}
	return h
}

func (r *HttpRequest) Request() *http.Request {
	return r.request
}

func (r *HttpRequest) Query() iweb.IQuery {
	if r.query == nil {
		r.query = NewRequestQuery(r.request)
	}
	return r.query
}

func (r *HttpRequest) Param() iweb.IParam {
	if r.param == nil {
		r.param = NewRequestParam(r.paramCache)
	}
	return r.param
}

func (r *HttpRequest) Body() iweb.IBody {
	if r.body == nil {
		r.body = NewRequestBody(r.request)
	}
	return r.body
}

func (r *HttpRequest) SetParam(params iweb.IRouterParams) {
	r.paramCache = params
}

func (r *HttpRequest) GetHeader(key string) string {
	return r.request.Header.Get(key)
}

func (r *HttpRequest) Path() string {
	return r.request.URL.Path
}

func (r *HttpRequest) SetPath(path string) {
	r.request.URL.Path = path
}

func (r *HttpRequest) Method() string {
	return r.request.Method
}

func (r *HttpRequest) RemoteIp() string {
	var (
		ip  string
		err error
	)
	if ip, _, err = net.SplitHostPort(strings.TrimSpace(r.request.RemoteAddr)); err != nil {
		return ""
	}
	return ip
}

func (r *HttpRequest) ClientIp() string {
	return ""
}

func (r *HttpRequest) ContentType() string {
	return utils.FilterFlags(r.request.Header.Get("Content-Type"))
}
